<?php

// wangling219 测试号 信息
define ("TOKEN", "leafan");
define("APPID", "wxab31157c01de5423");
define("APPSECRET", "0dad355ca6caffbafadef6202ce74b76");

require_once(dirname(__FILE__) . "/common/lib/lib_base.php");

// wangling219 测试号信息 end

class wechatEntry
{
    private $access_token="";
    private $menu_file = "menu.json";
    
	public function valid()
    {
        @$echoStr = $_GET["echostr"];

        //valid signature , option
        if($this->checkSignature()){
        	echo $echoStr;
        	return;
        }
    }
	
	private function checkSignature()
	{
		@$signature = $_GET["signature"];
		@$timestamp = $_GET["timestamp"];
		@$nonce = $_GET["nonce"];
					
		$token = TOKEN;
		$tmpArr = array($token, $timestamp, $nonce);
		sort($tmpArr, SORT_STRING);
		$tmpStr = implode( $tmpArr );
		$tmpStr = sha1( $tmpStr );

		if( $tmpStr == $signature )
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
    public function getAccessToken($appid, $appserect)
    {
        @$print_token = $_GET["print_token"];
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="
            . $appid . "&" . "secret=" . $appserect;
        
        $jsn = curl_get_url($url);
        $jsn = no_check_json_decode($jsn);
        
        if(!empty($jsn->access_token))
        {
            $this->access_token = $jsn->access_token;
            if($print_token != "")
            {
                echo "<br>token is: " . $this->access_token . "<br>";
            }
            
            return $jsn->access_token;
        }
        else
        {
            return null;
            exit(-1);
        }
    }
    
    public function getWxIPList()
    {
        if($this->access_token == "")
        {
            $this->getAccessToken(APPID, APPSECRET);
        }
        
        $url = "https://api.weixin.qq.com/cgi-bin/getcallbackip?access_token=" . $this->access_token;
        
        $jsn = curl_get_url($url);
        
        var_dump($jsn);
        
        $jsn = no_check_json_decode($jsn);
        
        if(!empty($jsn->ip_list))
        {
            return $jsn->ip_list;
        }
        else
        {
            return "<br>Error getWxIPList output<br>";
        }
    }
    
    // 创建微信菜单
    public function createMenu($json_file="")
    {
        if($json_file == "")
        {
            $json_file = $this->$menu_file;
        }
        
        $menu_json = file_get_contents($json_file, false, null, 0, 10240);
        if($menu_json=="" || !isJson($menu_json))
        {
            echo "<br>the menu_json is not a valid data. json_file is: " . $json_file 
                . ", json_data is:<br><br>" . $menu_json . "</br>";
            die();
        }
        
        if($this->access_token == "")
        {
            $this->getAccessToken(APPID, APPSECRET);
        }
        
        // 发送数据
        $url = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token=" . $this->access_token;
        $ret = curl_post_url($url, $menu_json);
    }
    
    
	// 代码留着，微信上的例子	
	public function responseMsg()
    {
		//get post data, May be due to the different environments
		$postStr = $GLOBALS["HTTP_RAW_POST_DATA"];
        file_put_contents("menu.log", $postStr, FILE_APPEND);
        
        $test_out = "<xml>
<ToUserName><![CDATA[o5uf7vhwgo5BA7poRU8NlE57oXD4]]></ToUserName>
<FromUserName><![CDATA[gh_f1c97932a2a0]]></FromUserName>
<CreateTime>1455511968</CreateTime>
<MsgType><![CDATA[text]]></MsgType>
<Content><![CDATA[你好，我们还在测试耶..]]></Content>
</xml>";
        
        echo $test_out;

      	//extract post data
		if (!empty($postStr)){
                /* libxml_disable_entity_loader is to prevent XML eXternal Entity Injection,
                   the best way is to check the validity of xml by yourself */
                libxml_disable_entity_loader(true);
              	$postObj = simplexml_load_string($postStr, 'SimpleXMLElement', LIBXML_NOCDATA);
                $fromUsername = $postObj->FromUserName;
                $toUsername = $postObj->ToUserName;
                $keyword = trim($postObj->Content);
                $time = time();
                $textTpl = "<xml>
							<ToUserName><![CDATA[%s]]></ToUserName>
							<FromUserName><![CDATA[%s]]></FromUserName>
							<CreateTime>%s</CreateTime>
							<MsgType><![CDATA[%s]]></MsgType>
							<Content><![CDATA[%s]]></Content>
							<FuncFlag>0</FuncFlag>
							</xml>";             
				if(!empty( $keyword ))
                {
              		$msgType = "text";
                	$contentStr = "Welcome to wechat world!";
                	$resultStr = sprintf($textTpl, $fromUsername, $toUsername, $time, $msgType, $contentStr);
                	echo $resultStr;
                }else{
                	echo "<br>Input something...<br>";
                }

        }else {
        	echo "";
        	exit;
        }
    }
}

$wx_obj = new wechatEntry();
// $wx_obj->valid();  -- 修改url配置时需要开启此输出

$wx_obj->getWxIPList();

/**
 * 微信各种调试接口测试记录
 
$wx_obj = new wechatEntry();

$wx_obj->valid();   // 调试微信的signature等信息是否正确

$wx_obj->getWxIPList(); // 获取微信服务器的所有ip地址（有好多）

$wx_obj->createMenu("menu.json");  // 发送自定义菜单到微信服务器上，菜单列表是 "menu.json" 中定义

$wx_obj->responseMsg(); // 回复数据


 */
?>